"""
    jwt 认证工具
"""
from datetime import timedelta, datetime, timezone
from typing import Optional

from jose import jwt
from passlib.context import CryptContext

from app.config import config

pwd_context  = CryptContext(schemes=["bcrypt"], deprecated="auto")


class JWTUtil:

    """
    jwt 认证工具
    """

    SECRET_KEY = config.jwt.secret_key
    ALGORITHM = config.jwt.algorithm
    ACCESS_TOKEN_EXPIRE_MINUTES = config.jwt.access_token_expire_minutes

    @staticmethod
    def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
        """
        创建token 令牌
        """
        to_encode = data.copy()
        if expires_delta:
            expire = datetime.now(timezone.utc) + expires_delta
        else:
            expire = datetime.now(timezone.utc) + timedelta(minutes=JWTUtil.ACCESS_TOKEN_EXPIRE_MINUTES)
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(to_encode, JWTUtil.SECRET_KEY, algorithm=JWTUtil.ALGORITHM)
        return encoded_jwt

    @staticmethod
    def decode_token(token: str) -> dict:
        """解码JWT令牌"""
        return jwt.decode(
            token,
            JWTUtil.SECRET_KEY,
            algorithms=[JWTUtil.ALGORITHM]
        )
    @staticmethod
    def verify_password(plain_password: str, hashed_password: str) -> bool:
        """验证密码"""
        return pwd_context.verify(plain_password, hashed_password)

    @staticmethod
    def get_password_hash(password: str) -> str:
        """生成密码哈希"""
        return pwd_context.hash(password)
